import { reqAddressList, reqDeleteAddress } from '../../../api/address'
import { modal, toast } from '../../../../../utils/expendApi'
import { swiperCellBehavior } from '../../../../../behaviors/swiperCell'
const app = getApp()
Page({
  behaviors: [swiperCellBehavior],
  data: {
    addressList: [],
  },
  // 获取列表
  async getAddressList () {
    const { data: addressList } = await reqAddressList()
    this.setData({
      addressList
    })
  },

  // 去编辑页面
  toEdit(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },
  // 删除
  async delAddress (e) {
    const { id } = e.currentTarget.dataset
    const modres = await modal({
      content: '确认删除该地址吗?'
    })
    if(modres) {
      const delres = await reqDeleteAddress(id)
      toast({title: '删除成功'})
      this.getAddressList()
    }
  },
  // 选择地址并返回上一级页面
  changeAddress (e) {
    // flag标识,是为了区分是否从结算支付页面进入的收货地址列表页面
    // 如果是,在点击收货地址时,就需要给全局address赋值 
    if(this.flag !== '1') return
    const addressId = e.currentTarget.dataset.id

    // 根据id从地址列表中查询当前地址
    const selectAddress = this.data.addressList.find(item => item.id === addressId)
    if(selectAddress) {
      app.globalData.address = selectAddress
      wx.navigateBack()
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.flag = options.flag
  },
  onShow() {
    this.getAddressList()
  }
})